package demo.db;

/**
 * Created by hdt3213 on 17/8/18.
 */
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.*;
import java.util.List;

public class UserDao {

	SqlSession session;
	UserMapper mapper;

	public UserDao(SqlSession session) {
		this.session = session;
		mapper = session.getMapper(UserMapper.class);
	}

	int add(User user) {
		return mapper.insert(user);
	}

	int delete(User user) {
		return mapper.delete(user);
	}

	int update(User user) {
		if (mapper.exists(user.getId()) > 0) {
			return mapper.update(user);
		}
		return 0;
	}

	User select(int id) {
		List<User> users = mapper.find(id);
		if (users.size() > 0) {
			return users.get(0);
		}
		return null;
	}

	static SqlSession getSession() throws Exception {
		String resource = "src/main/java/demo.db/demo.db.xml";
		FileInputStream is = new FileInputStream(new File(resource));
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		factory.getConfiguration().addMapper(UserMapper.class);
		return factory.openSession();
	}

	public static void main(String[] args) throws Exception {
		User user = new User();
		user.setUsername("test");
		user.setPassword("test");

		SqlSession session = getSession();
		UserDao dao = new UserDao(session);
		dao.add(user);
		session.commit();
	}
}
